/**
 *  2013-5-15   上午11:17:02
 *  Created By niexiaoqiang
 */

package com.xiaoqiang.network;

import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

/**
 * TODO Add Class Description
 */
public class MtwServer {

	private boolean running;
	private List<ConnectedClient> clients;
	private ServerSocket svrSocket;
	private int serverPort=12001;
	private static Logger log = Logger.getLogger(MtwServer.class);

	public MtwServer() {
		this.running = true;
		this.clients = new ArrayList<ConnectedClient>();
	}

	public boolean isRunning() {
		return running;
	}

	public void run() {
		try {
			this.svrSocket = new ServerSocket(serverPort);
			log.info("Server started on " + new java.sql.Date(new Date().getTime()));
			while (running) {
				Socket cltSocket = this.svrSocket.accept();
				// 保存客户端的连接
				InetAddress ip = cltSocket.getInetAddress();
				int port = cltSocket.getPort();
				ConnectedClient client = new ConnectedClient(ip, port);
				this.clients.add(client);
				log.info(ip + " connected.");
				log.debug("there are "+(this.clients.size())+" users is online");
				// 为每个客户端开一个线程
				MyMsgRecivedListener listener=new MyMsgRecivedListener();
				RequestProcessor requestProcessor=new RequestProcessor(this, cltSocket,ip);
				requestProcessor.addMsgRecivedListener(listener);
				log.debug(ip + " add listener.");
				new Thread(requestProcessor).start();
			}
		} catch (Exception e) {
			this.running = false;
		}
	}

	private static class ConnectedClient {
		public InetAddress ip;
		public int port;

		public ConnectedClient(InetAddress ip, int port) {
			super();
			this.ip = ip;
			this.port = port;
		}

		@Override
		public boolean equals(Object obj) {
			if (obj instanceof ConnectedClient) {
				ConnectedClient c = (ConnectedClient) obj;
				return c.ip.equals(this.ip) && c.port == this.port;
			}
			return false;
		}
	}
}
